﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;

namespace WS.EKA.UI.Business
{
    internal class MessagePublisherImpl : IPush
    {
        static Dictionary<WebSocketClientType, IReceive> receivers = null;
        static object obj = new object();

        static MessagePublisherImpl()
        {
            receivers = new Dictionary<WebSocketClientType, IReceive>();
            RegisteReceiver();
        }

        private static void RegisteReceiver()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var types = assembly.GetTypes();
            foreach (var type in types)
            {
                if (type.IsClass && type.GetInterface("IReceive") != null)
                {
                    var obj = Activator.CreateInstance(type) as IReceive;
                    receivers[obj.Key] = obj;
                }
            }
        }

        public void Push<Model>(Model m, WebSocketClientType type)
        {
            if (WebSocketClientType.None == type)
            {
                Push<Model>(m);
                return;
            }
            receivers[type].Receive<Model>(m);
        }

        public void Push<Model>(Model m)
        {
            throw new NotImplementedException();
        }

        public void AddReceive(IReceive target)
        {
            if (!receivers.ContainsKey(target.Key))
            {
                lock (obj)
                {
                    if (!receivers.ContainsKey(target.Key))
                    {
                        receivers[target.Key] = target;
                    }
                }
            }
        }

        public void RemoveReceive(IReceive target)
        {
            receivers.Remove(target.Key);
        }
    }
}
